<template>
  <van-cell class="comment-item-container">
    <template #icon>
      <van-image
        round
        class="avatar"
        fit="cover"
        :src="comment.aut_photo"
      />
    </template>

    <template #title>
      <span class="title">{{ comment.aut_name }}</span>
    </template>

    <template #label>
      <p class="comment-content">{{ comment.content }}</p>
      <div class="bottom-info">
        <span class="comment-pubdate">{{ comment.pubDate | relativeTime }}</span>
        <van-button
          class="comment-info"
          round type="default"
          size="mini"
          @click="$emit('replyClick')"
        >
          回复 {{ comment.reply_count }}
        </van-button>
      </div>
    </template>

    <template #default>
      <van-button
        class="reply-btn"
        :icon="comment.is_liking ? 'good-job' : 'good-job-o'"
        :style="{ color: comment.is_liking ? '#e5645f' : '#222' }"
        size="mini"
        :loading="commentLoading"
        @click="onCommentLike"
      >
        {{ comment.like_count === 0 ? '赞' : comment.like_count }}
      </van-button>
    </template>
  </van-cell>
</template>

<script>
import { addCommentLikeAPI, deleteCommentLikeAPI } from '@/api'

export default {
  name: 'CommentItem',
  props: {
    comment: {
      type: Object,
      default: () => ({})
    }
  },

  data () {
    return {
      commentLoading: false, // 点赞功能加载状态
      commentClone: this.comment
    }
  },
  methods: {
    // 评论点赞或取消点赞
    async onCommentLike () {
      console.log(this.comment)
      try {
        // 调用接口前的加载状态
        this.commentLoading = true

        if (this.comment.is_liking) {
          // 已点赞，需要取消点赞
          await deleteCommentLikeAPI(this.comment.com_id)
          // 点赞数-1
          this.commentClone.like_count--
        } else {
          // 未点赞，需要添加点赞
          await addCommentLikeAPI({
            target: this.comment.com_id
          })
          // 点赞数+1
          this.commentClone.like_count++
        }

        // 修改当前用户对目标评论的点赞状态
        this.commentClone.is_liking = !this.comment.is_liking
      } catch (error) {
        console.log(error)
        this.$toast.fail('网络异常，请稍后重试！')
      }

      // 关闭加载状态
      this.commentLoading = false
    }
  }
}
</script>

<style scoped lang="less">
.comment-item-container {
  .avatar {
    width: 36px;
    height: 36px;
    margin-right: 12px;
  }

  .title {
    color: #406599;
    font-size: 13px;
  }

  .comment-content {
    font-size: 12px;
  }

  .bottom-info {
    display: flex;
    align-items: center;

    .comment-pubdate {
      color: #222;
      margin-right: 14px;
    }

    .comment-info {
      color: #222;
      width: 67.5px;
    }
  }

  .reply-btn {
    font-size: 10px;
    border: none;
  }
}
</style>
